package com.tude._07vehicle.controller;

import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.tude._07vehicle.base.response.JsonResult;
import com.tude._07vehicle.base.response.StatusCode;
import com.tude._07vehicle.mapper.UserMapper;
import com.tude._07vehicle.pojo.dto.UserLoginParam;
import com.tude._07vehicle.pojo.dto.UserRegParam;
import com.tude._07vehicle.pojo.entity.User;
import com.tude._07vehicle.pojo.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import java.util.Date;

@Api(tags = "01.用户模块")
@Slf4j
@RestController
@RequestMapping("/v1/user/")
public class UserController {

    @Autowired
    private UserMapper userMapper;

    @ApiOperation("用户注册")
    @ApiOperationSupport(order = 10)
    @PostMapping("reg")
    public JsonResult reg(@RequestBody @Validated UserRegParam param) {
        String username = param.getUsername();
        int num = userMapper.selectUserByName(username);
        if (num > 0) {
            return new JsonResult(StatusCode.USERNAME_EXISTS);
        }
        User user = new User();
        BeanUtils.copyProperties(param, user);
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());
        userMapper.insertUser(user);
        return JsonResult.ok();
    }

    @ApiOperation("用户登录")
    @ApiOperationSupport(order = 20)
    @PostMapping("login")
    public JsonResult login(@RequestBody UserLoginParam loginParam, @ApiIgnore HttpSession session){
        UserVO userVO = userMapper.selectUser(loginParam);
        if (userVO == null){
            return new JsonResult(StatusCode.USERNAME_PASSWORD_ERROR);
        }
        // 实际中key一定是唯一的，这里为了方便演示，就用user作为key（以后基本都用JWT）
        session.setAttribute("user",userVO);
        return JsonResult.ok(userVO);
    }

    @ApiOperation("获取当前用户")
    @ApiOperationSupport(order = 30)
    @GetMapping("currentUser")
    public JsonResult currentUser(@ApiIgnore HttpSession session){
        UserVO userVO = (UserVO) session.getAttribute("user");
        return JsonResult.ok(userVO);
    }

    @ApiOperation("用户退出")
    @ApiOperationSupport(order = 40)
    @GetMapping("logout")
    public void logout(@ApiIgnore HttpSession session){
        session.removeAttribute("user");
    }
}
